<template>
  <!-- 实物商品组件 -->
  <div>
    <!-- 商品详情 -->
    <div>
      <div
        class="background_gray padding_15 margin_top_20"
        style="border-radius: 5px; font-weight: 600"
      >
        详情信息
      </div>
      <!-- 条码 -->
      <label class="flex_y_center margin_top_20">
        <div class="inp_title">
          <span>*</span>
          条码：
        </div>
        <div style="width: 15%">
          <el-input v-model="realForm.goods_code" placeholder="请输入条码" />
        </div>
      </label>
      <!-- 配送方式 -->
      <div class="margin_top_20" style="display: flex">
        <div class="inp_title">
          <span>*</span>
          配送方式：
        </div>
        <div>
          <el-radio-group
            v-model="realForm.delivery_method"
            style="
              display: flex;
              flex-direction: column;
              justify-content: space-between;
            "
          >
            <el-radio label="express">快递发货</el-radio>
            <el-radio label="shop" style="margin: 15px 0">到店自取</el-radio>
          </el-radio-group>
        </div>
      </div>
      <!-- 运费 -->
      <label class="flex_y_center">
        <div class="inp_title">
          <span v-if="realForm.delivery_method != 'shop'">*</span>
          运费：
        </div>
        <div style="width: 15%">
          <el-input
            v-model="realForm.express_fee"
            :disabled="realForm.delivery_method != 'express'"
            placeholder="请输入运费"
          />
        </div>
      </label>
    </div>
    <!-- 商品规格信息 -->
    <div>
      <div
        class="background_gray padding_15 margin_top_20"
        style="border-radius: 5px; font-weight: 600"
      >
        价格
      </div>
      <div class="margin_top_20" style="display: flex">
        <div class="inp_title">商品规格：</div>
        <div class="form_group">
          <div
            v-for="(attr, index) in attrs"
            :key="`attr${index}`"
            class="form-item"
          >
            <div class="form_title">
              <el-input
                v-model="attr.pName"
                placeholder="规格名"
                style="width: 200px"
              />
              <span class="delete" @click="delSpec(index)">×</span>
            </div>
            <ul class="form_list">
              <li
                v-for="(item, index2) in attr.spec"
                :key="`item${index2}`"
                style="position: relative"
              >
                <el-input v-model="item.cName" placeholder="请输入规格值" />
                <img
                  src="https://s3.bmp.ovh/imgs/2021/12/f9c23395fd269f6a.png"
                  style="
                    width: 13px;
                    height: 13px;
                    position: absolute;
                    top: -4px;
                    right: -4px;
                    cursor: pointer;
                  "
                  @click="delItem(index, index2)"
                />
              </li>
            </ul>
            <div style="padding: 0 10px 10px">
              <el-link type="primary" @click="addAttrsSpec(index)">
                添加规格值
              </el-link>
            </div>
          </div>
          <div class="flex_y_center" style="padding: 10px; background: #f8f8f8">
            <div v-show="attrs.length != 3" style="margin-right: 5px">
              <el-button @click="addItem">添加规格项目</el-button>
            </div>
            <div v-show="attrs.length != 0">
              <el-button type="danger" @click="clearItem">
                清空全部规格
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <div v-show="tableData" class="form_table">
        <div class="inp_title">商品明细：</div>
        <div style="width: 100%">
          <!-- 规格明细 -->
          <table border="1px solid #ccc">
            <thead>
              <tr>
                <th v-for="(list, index) in tableData" :key="`list${index}`">
                  {{ list['pName'] }}
                </th>
                <th>价格</th>
                <th>条码</th>
              </tr>
            </thead>
            <tbody>
              <!-- 这里做了改动将 v-if 替换成了 v-show -->
              <tr v-for="(row, index) in rows" :key="`row${index}`">
                <td
                  v-for="(item, index2) in tableData"
                  v-show="!((row - 1) % item['rowspan'])"
                  :key="`item${index2}`"
                  :rowspan="item['rowspan']"
                >
                  {{ item | getName(row) }}
                </td>
                <td>
                  <input
                    v-model="
                      realForm.goods_spec[row - 1]['attribute_item_price']
                    "
                    placeholder="请输入价格"
                  />
                </td>
                <td>
                  <input
                    v-model="realForm.goods_spec[row - 1]['goods_code']"
                    placeholder="请输入明细"
                  />
                </td>
              </tr>
            </tbody>
          </table>
          <!-- 批量设置 -->
          <div class="flex_y_center" style="padding: 10px 0 0">
            <p style="margin-right: 5px">批量设置：</p>
            <el-link type="primary" @click="batchClick">价格</el-link>
            <div
              v-show="batchBool"
              class="flex_y_center"
              style="margin-left: 5px"
            >
              <el-input
                v-model="batchVal"
                placeholder="请输入需批量设置的价格"
                style="margin-right: 5px"
              />
              <el-button @click="batchBool = false">取消</el-button>
              <el-button type="primary" @click="batchEndow">确定</el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 价格 -->
      <label>
        <div class="flex_y_center" style="margin-top: 20px">
          <div class="inp_title">价格：</div>
          <div style="width: 15%">
            <el-input
              v-model="realForm.goods_price"
              :disabled="realForm.is_many_attribute == 'Y'"
              placeholder="请输入价格"
            >
              <template slot="prepend">￥</template>
            </el-input>
          </div>
        </div>
      </label>

      <!-- 积分率 -->
      <label>
        <div class="flex_y_center" style="margin-top: 20px">
          <div class="inp_title">积分率：</div>
          <div style="width: 15%">
            <el-input
              v-model="realForm.goods_points"
              placeholder="请输入积分率"
            >
              <template slot="append">%</template>
            </el-input>
          </div>
        </div>
      </label>
    </div>
    <!-- 提醒 -->
    <div>
      <div
        class="background_gray padding_15 margin_top_20"
        style="border-radius: 5px; font-weight: 600"
      >
        提醒
      </div>
      <!-- 预约提醒 -->
      <div class="margin_top_20 flex_y_center">
        <div class="inp_title">预约提醒：</div>
        <div>
          <el-radio-group v-model="realForm.is_remind" @change="chooseRemind">
            <el-radio label="N">关闭</el-radio>
            <el-radio label="Y" style="margin: 15px 0">开启</el-radio>
          </el-radio-group>
        </div>
      </div>
      <div v-show="realForm.is_remind == 'Y'">
        <!-- 商品提醒 -->
        <div class="margin_top_20" style="display: flex">
          <div class="inp_title">
            <span>*</span>
            商品提醒：
          </div>
          <div style="width: 92%">
            <el-table :data="realForm.goods_remind" width="100%">
              <el-table-column align="center" label="提醒类型">
                <template slot-scope="scope">
                  <el-select
                    v-model="scope.row.remind_type"
                    placeholder=" "
                    @change="chooseRemindItems(scope.row)"
                  >
                    <el-option label="日周期" value="day" />
                    <el-option label="周周期" value="week" />
                    <el-option label="月周期" value="month" />
                    <el-option label="季周期" value="quarter" />
                    <el-option label="年周期" value="year" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column align="center" label="周期间隔">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.remind_value" placeholder=" " />
                </template>
              </el-table-column>
              <el-table-column align="center" label="有效期">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.effective_term"
                    placeholder=" "
                  />
                </template>
              </el-table-column>
              <el-table-column align="center" label="提醒次数">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.effective_num" placeholder=" " />
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    @click="
                      realForm.goods_remind.length == 1
                        ? $message.error('至少保留一项')
                        : realForm.goods_remind.splice(scope.$index, 1)
                    "
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-button
              style="margin-top: 10px"
              type="primary"
              @click="addRemindItems"
            >
              添加周期提醒
            </el-button>
          </div>
        </div>
        <!-- 提醒内容 -->
        <div class="margin_top_20" style="display: flex">
          <div class="inp_title title_pos">
            <span>*</span>
            提醒内容：
          </div>
          <div>
            <div
              v-for="(item, index) of fieldsArr"
              :key="index"
              class="flex_y_center"
              style="margin-bottom: 10px"
            >
              <el-input
                v-model="item.txt"
                placeholder="请输入提醒标题"
                style="width: 50%"
              />
              <div style="margin: 0 10px">文本</div>
              <el-button type="text" @click="fieldsArr.splice(index, 1)">
                删除
              </el-button>
            </div>
            <el-button type="text" @click="fieldsArr.push({ txt: '' })">
              添加提醒周期
            </el-button>
          </div>
        </div>
        <!-- 商品留言 -->
        <div class="margin_top_20 flex_y_center">
          <div class="inp_title">
            <span>*</span>
            商品留言：
          </div>
          <div>
            <el-input
              v-model="realForm.remind_advance"
              placeholder="请输入商品留言"
            />
          </div>
        </div>
      </div>
    </div>
    <!-- 商品属性 -->
    <div style="margin-top: 15px">
      <div
        class="background_gray padding_15"
        style="border-radius: 5px; font-weight: 600"
      >
        商品属性
      </div>

      <!-- 营销方式 -->
      <div style="padding: 15px 0; display: flex">
        <!-- 单选 -->
        <div class="inp_title">
          <span>*</span>
          营销方式：
        </div>
        <div class="flex_direction">
          <el-radio v-model="realForm.expire_type" label="sale_at">
            销售日期
          </el-radio>
          <el-radio
            v-model="realForm.expire_type"
            label="facture_at"
            style="margin: 15px 0"
          >
            出厂时间
          </el-radio>
          <el-radio v-model="realForm.expire_type" label="long_at">
            永久有效
          </el-radio>
        </div>
      </div>
      <!-- 有效期输入框 -->
      <label class="flex_y_center">
        <div class="inp_title">
          <span v-if="realForm.expire_type != 'long_at'">*</span>
          有效期：
        </div>
        <el-input
          v-model="realForm.effective_at"
          :disabled="
            realForm.expire_type == 'long_at' || realForm.expire_type == ''
          "
          placeholder="请输入有效期天数"
          style="width: 15%"
        >
          <template slot="append">天</template>
        </el-input>
      </label>

      <!-- 开售时间 -->
      <div class="flex_y_center margin_top_20">
        <div class="inp_title">
          <span>*</span>
          开售时间：
        </div>
        <div>
          <el-radio v-model="realForm.goods_status" label="on">
            立即开售
          </el-radio>
          <el-radio v-model="realForm.goods_status" label="off">
            放入仓库
          </el-radio>
        </div>
      </div>

      <!-- 商品详情 -->
      <div class="margin_top_20" style="display: flex">
        <div class="inp_title">商品详情：</div>
        <Vue-editor
          :goods-desc="realForm.goods_content"
          @sendText="goodsContent"
        />
      </div>
    </div>
    <!-- 添加商品 -->
    <div style="width: fit-content; margin: 20px auto 0">
      <el-button type="primary" @click="searchForm">保存</el-button>
    </div>
  </div>
</template>

<script>
  export default {
    components: {
      VueEditor: () => import('./editor.vue'),
    },
    // 过滤器
    filters: {
      getName(obj, index) {
        if (obj) {
          var r = parseInt((index - 1) / obj['rowspan'])
          var l = obj['specLen'] || 1
          var key = r % l
          return obj['spec'] && obj['spec'][key] && obj['spec'][key]['cName']
        }
      },
    },
    props: {
      oGoodsDetailsInfo: {
        type: Object,
        default() {
          return {}
        },
      },
    },
    data() {
      return {
        attrs: [],
        batchBool: false,
        batchVal: '',
        fieldsArr: [],

        realForm: {
          goods_code: '', // 商品条码
          delivery_method: 'shop', // 配送方式
          express_fee: '0', // 运费
          is_many_attribute: 'N', // 是否多规格
          goods_spec: [],
          goods_attr: [],
          goods_price: '0.00', // 商品价格
          goods_points: 100, // 商品积分率
          is_remind: 'N', // 提醒开关 Y开启 N关闭
          goods_remind: [], // 商品提醒数据
          remind_fields: [], // 到期提醒内容
          remind_advance: '1', // 商品留言
          expire_type: 'long_at', // 营销方式 sale_at销售日期, facture_at出厂日期, long_at长期
          effective_at: '', // 有效期
          goods_status: 'on', // 开售时间
          goods_content: '', // 商品详情
        },
        hint: {
          goods_code: '商品条码',
          delivery_method: '配送方式',
          expire_type: '营销方式',
          goods_status: '开售时间',
        },
      }
    },
    // 计算表格相关数据
    computed: {
      // 计算出表格需要展示的数据格式，每一列需要合并多少单元格
      tableData() {
        var attrs = this.attrs
        var len = attrs.length // 用户添加了几个规格
        // 判断如果没有添加的话那么，return出去
        if (len == 0) {
          return
        }
        var tData = []
        //初始化tableData
        for (var i = 0; i < len; i++) {
          var row = {}
          row['pName'] = attrs[i]['pName']
          row['spec'] = []
          var len2 = attrs[i]['spec'].length
          var specLen = 0
          for (var j = 0; j < len2; j++) {
            var spe = {}
            var cName = attrs[i]['spec'][j]['cName']
            if (!cName) {
              continue
            }
            ++specLen
            spe['cName'] = cName
            row['spec'].push(spe)
          }
          row['specLen'] = specLen
          tData.push(row)
        }
        //计算，获取rowspan
        for (var k = 0, len3 = tData.length; k < len3; k++) {
          var rowspan = 1
          for (var k1 = k + 1; k1 < len3; k1++) {
            var kSpecLen = tData[k1]['specLen'] || 1
            rowspan *= kSpecLen
          }
          tData[k]['rowspan'] = rowspan
        }
        return tData
      },
      // 计算规格总长度
      rows() {
        if (!this.tableData) {
          return
        }
        var rows = 1
        var tableData = this.tableData
        var len = tableData.length
        for (var i = 0; i < len; i++) {
          var specLen = tableData[i]['specLen'] || 1
          rows *= specLen
        }
        //每条rowspan都为1情况
        if (rows == 1) {
          return tableData[0]['spec'].length
        }
        return rows
      },
    },
    watch: {
      tableData() {
        if (!this.tableData) {
          return []
        }
        var rows = this.rows // 总行数
        var tList = [] // 空数组用来存放构建的数据
        var srcData = this.tableData
        for (var i = 0; i < rows; i++) {
          var listItem = { attribute_item_name: '' }
          //构建动态项
          for (var j = 0; j < srcData.length; j++) {
            //构造第一类目
            // var key = srcData[j]['pName']
            var rowspan = srcData[j]['rowspan']
            var len = srcData[j]['specLen']
            if (!len) {
              continue
            }
            var spec = srcData[j]['spec']
            var index = parseInt(i / rowspan) % len
            // 将数据拼接
            listItem['attribute_item_name'] += spec[index]['cName'] + '-'
          }
          if (JSON.stringify(this.oGoodsDetailsInfo) != '{}') {
            listItem['attribute_item_price'] =
              this.realForm.goods_spec[i].item_price
            listItem['goods_code'] = this.realForm.goods_spec[i].goods_code
          } else {
            listItem['attribute_item_price'] = ''
            listItem['goods_code'] = ''
          }
          tList.push(listItem)
        }
        // 去掉 attribute_item_name 下的最后一个 - 字符
        for (let item of tList) {
          item['attribute_item_name'] = item['attribute_item_name'].slice(
            0,
            item['attribute_item_name'].length - 1
          )
        }
        this.count++
        this.realForm.goods_spec = tList

        // 构建 goods_attr 字段的值
        let tArr = []
        for (let i = 0; i < srcData.length; i++) {
          for (let j = 0; j < srcData[i].spec.length; j++) {
            let test = {}
            this.$set(test, 'attribute_name', srcData[i].pName)
            this.$set(test, 'attribute_value', srcData[i].spec[j].cName)
            tArr.push(test)
          }
        }
        this.realForm.goods_attr = JSON.stringify(tArr)
      },
      // 监视 attrs 的变化，用于判断该添加商品是否是多规格
      attrs(newValue) {
        // 每次 attrs 发生改变后都进行判断，如果长度不为0的话那么将价格，供货价，条码选项框禁用，并清空数值
        if (newValue.length != 0) {
          this.realForm.is_many_attribute = 'Y'
        } else {
          this.realForm.is_many_attribute = 'N'
          this.realForm.goods_attr = []
          this.realForm.goods_spec = []
        }
      },
      'realForm.expire_type'(newValue) {
        if (newValue == 'long_at') {
          this.realForm.effective_at = ''
        }
      },
    },
    created() {
      this.assignForm()
    },
    methods: {
      // 将需要的数据赋值到相同属性值上
      assignForm() {
        if (JSON.stringify(this.oGoodsDetailsInfo) != '{}') {
          for (let item in this.realForm) {
            if (item != 'goods_attr') {
              // 判断是否是
              if (
                item == 'remind_fields' &&
                this.oGoodsDetailsInfo.remind_fields != null
              ) {
                for (let item of this.oGoodsDetailsInfo.remind_fields) {
                  this.fieldsArr.push({ txt: item })
                }
              } else {
                this.realForm[item] = this.oGoodsDetailsInfo[item]
              }
            }
          }
          this.attrs = this.oGoodsDetailsInfo.goods_attr
        }
      },
      // 商品规格
      // 添加商品规格项
      addItem() {
        var obj = {
          pName: '',
          rowspan: 1,
          spec: [{ cName: '' }],
        }
        if (this.attrs.length >= 3) {
          return
        }
        this.attrs.push(obj)

        this.realForm.goods_price = '0.00'
      },
      // 删除规格项
      delSpec(index) {
        this.attrs.splice(index, 1)
      },
      // 清空全部规格
      clearItem() {
        this.attrs = []
      },
      // 添加商品规格值
      addAttrsSpec(index) {
        this.attrs[index].spec.push({ spec: '' })
      },
      // 删除指定规格值
      delItem(fatherIndex, sonIndex) {
        // 判断当前删除的规格值是否在该规格项是最后一个
        if (this.attrs[fatherIndex].spec.length == 1) {
          this.$message.warning(
            this.attrs[fatherIndex].pName + '规格值最少保留一个'
          )
        } else {
          this.attrs[fatherIndex].spec.splice(sonIndex, 1)
        }
      },
      // 控制批量设置价格输入框显示隐藏
      batchClick() {
        this.batchBool = true
        this.batchVal = ''
      },
      // 批量设置规格价格
      batchEndow() {
        if (this.realForm.goods_spec.length == 0) {
          this.$message.warning('请先添加规格值')
        } else {
          for (let item of this.realForm.goods_spec) {
            item.attribute_item_price = this.batchVal
          }
        }
        this.batchBool = false
      },

      chooseRemind(e) {
        if (e == 'N') {
          this.realForm.goods_remind = []
          this.realForm.remind_fields = []
          this.realForm.remind_advance = ''
        } else {
          this.realForm.goods_remind = [
            {
              remind_type: '',
              remind_value: '',
              effective_term: '',
              effective_num: '',
            },
          ]
        }
      },
      // 选择提醒周期类型
      chooseRemindItems(row) {
        switch (row.remind_type) {
          case 'day':
            row.remind_value = 1
            break
          case 'week':
            row.remind_value = 7
            break
          case 'month':
            row.remind_value = 30
            break
          case 'quarter':
            row.remind_value = 90
            break
          case 'year':
            row.remind_value = 365
            break
        }
      },
      // 添加周期提醒项
      addRemindItems() {
        this.realForm.goods_remind.push({
          remind_type: '',
          remind_value: '',
          effective_term: '',
          effective_num: '',
        })
      },

      // 检查form表单数据是否有漏输
      searchForm() {
        for (let item in this.hint) {
          if (this.realForm[item] == '') {
            this.$message.error(this.hint[item] + '未填写')
            break
          }
        }
        // 判断配送方式，和运费
        if (this.realForm.delivery_method == 'express') {
          if (this.realForm.express_fee == '') {
            this.$message.error('运费未输入')
            return false
          }
        }
        // 检索规格
        if (this.realForm.is_many_attribute == 'N') {
          if (this.realForm.goods_price == '') {
            this.$message.error('商品价格未输入')
            return false
          }
        }
        // 检索营销方式
        if (this.realForm.expire_type != 'long_at') {
          if (this.realForm.effective_at == '') {
            this.$message.error('有效期未输入')
            return false
          }
        }
        // 检索预约提醒
        if (this.realForm.is_remind == 'Y') {
          for (let item of this.realForm.goods_remind) {
            for (let itemChild in item) {
              if (item[itemChild] == '') {
                this.$message.error('提醒内容未填写完整')
                return false
              }
            }
          }
          if (this.fieldsArr.length == 0) {
            this.$message.error('请填写提醒内容')
            return
          } else {
            for (let item of this.fieldsArr) {
              if (item.txt == '') {
                this.$message.error('提醒内容未填写完整')
                return false
              }
            }
            this.realForm.remind_fields = []
            for (let item of this.fieldsArr) {
              this.realForm.remind_fields.push(item.txt)
            }
          }
          if (this.realForm.remind_advance == '') {
            this.$message.error('商品留言未填写')
            return
          }
        }

        // 将用户输入的保存，传递给父组件
        this.$emit('sendData', this.realForm)
      },
      goodsContent(text) {
        this.realForm.goods_content = text
      },
    },
  }
</script>

<style scoped>
  .padding_15 {
    padding: 15px;
  }
  .flex_direction {
    display: flex;
    flex-direction: column;
  }
  span {
    color: red;
  }
  .background_gray {
    background-color: rgb(248, 248, 248);
  }
  .color_shall_gray {
    color: rgba(0, 0, 0, 0.8);
  }
  .margin_top_20 {
    margin-top: 20px;
  }
  .inp_title {
    width: 80px;
    text-align: right;
  }
  .title_pos {
    position: relative;
    top: 7px;
  }
  /**/
  .form_title {
    background: #f8f8f8;
    padding: 10px;
    position: relative;
  }
  .form_title .label {
    color: #999;
  }
  .form_title .delete {
    width: 20px;
    height: 20px;
    line-height: 20px;
    border: 1px solid #ccc;
    border-radius: 50%;
    position: absolute;
    right: 15px;
    top: 50%;
    margin-top: -10px;
    text-align: center;
    color: #fff;
    background: #ccc;
    cursor: pointer;
  }
  .form_list {
    padding: 0 10px;
    display: grid;
    grid-template-columns: repeat(6, 1fr);
    grid-gap: 10px;
    list-style: none;
  }
  .form_group {
    width: 100%;
    border: 1px solid #ccc;
    padding: 10px;
  }
  .form_table {
    margin-top: 10px;
    display: flex;
  }

  /*table*/
  table,
  th,
  td {
    border: 1px solid #f0f0f0;
    border-collapse: collapse;
    text-align: start;
    padding: 14px;
  }
  table {
    width: 100%;
  }
  th {
    background-color: #fafafa;
  }
  tr:hover {
    background-color: #dad8d87e;
  }

  /* input */
  input {
    width: 100%;
    padding: 7px;
    border: 1px solid rgba(0, 0, 0, 0.1);
    color: rgba(0, 0, 0, 0.5);
  }
  .disabled_inp {
    cursor: no-drop;
  }
</style>
